using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;

namespace HW2and3
{
    class KTModelDFS : ModelBase
    {
        private int[] vertical = {-1, -2, -2, -1, 1, 2, 2, 1};
        private int[] horizontal = {2, 1, -1, -2, -2, -1, 1, 2};
        private bool[,] visited;

        public KTModelDFS() { }

        public override void Initialize(int sleepInterval, int size, int x, int y)
        {
            base.Initialize(sleepInterval, size, x, y);

            modelThread = new Thread(this.DFSStart);

            visited = new bool[size, size];
            for (int i = 0; i < size; i++)
                for (int j = 0; j < size; j++)
                    visited[i, j] = false;
        }

        private void DFSStart()
        {
            KTStateKnight state = new KTStateKnight(size,x,y,false);
            Console.WriteLine("Iniciando el DFS");

            DFS(state);
        }


        public bool DFS(KTStateKnight prevState)
        {
            if (this.isStopped) return false;
            Sleep();

            NotifyAll(prevState, (" X : " + (prevState.X) + " Y: " +  (prevState.Y)), "");
            if (visited[prevState.X, prevState.Y])
            {
                Console.WriteLine("{0},{1} - ha sido visitado", prevState.X, prevState.Y);
                return false;
            }
            else
            {
                Console.WriteLine("{0},{1} - No Ha sido visitado", prevState.X, prevState.Y);
                visited[prevState.X, prevState.Y] = true;
            }

            //Goal
            if (prevState.Index == size * size)
            {
                NotifyAll(prevState, "Fin", "Terminamos");
                return true;
            }

            for (int i = 0; i < horizontal.Length; i++)
            {
                int a = prevState.X + vertical[i];
                int b = prevState.Y + horizontal[i];
                if (a >= 0 && a < size && b >= 0 && b < size && prevState.Board[a,b] == 0)
                {
                    if (DFS(prevState.GetNewState(a, b)))
                        return true;
                }
            }
            visited[prevState.X, prevState.Y] = false;
            prevState.Index = (short)(prevState.Index - 1);
            NotifyAll(prevState, "Regresamos", "");
            return false;
        }
    }
}
